<?php
namespace QnuiRings\Controller;
use Think\Controller;
// 软件名称：微折软件-连环折扣
// 代码日期：v3.0 2017-7-9
// 作者：杨道泉 
// 文件名：QnuiRingsAction.class.php 
// 功能： 使用千牛UI发布限时折扣

class QnuiRingsController extends QnuiBaseController {
	public function index(){
		
		$this->display();
	}
	public function apply_tag(){
		//tmall.promotag.tag.find
		$tag_name = I("tag_name");
		$tag_desc = I("tag_desc");
		$start_time = date("Y-m-d H:i:s",(I("start_time")));
		$end_time = date("Y-m-d H:i:s",(I("end_time")));
		Vendor('taobaosdk/top/request/TmallPromotagTagApplyRequest');
		$req = new \TmallPromotagTagApplyRequest;
		$req->setTagName($tag_name);
		$req->setTagDesc($tag_desc);
		$req->setStartTime($start_time);
		$req->setEndTime($end_time);
		
		$resp = pre_resp($this->c->execute($req, session("TOP_SESSION")));
		if($resp->sub_code){
			$resp->sub_msg.="。可能已经被创建过了，请换个名字重试";
		}
		$this->ajaxReturn($resp);
	}
	public function find_tags(){
		$page_size = I("page_size");
		$page = I("page");
		$tag_name = I("tag_name");
		$tag_id = I("tag_id");
		Vendor('taobaosdk/top/request/TmallPromotagTagFindRequest');
		$req = new \TmallPromotagTagFindRequest;
		$req->setPageNo($page?$page:1);
		$req->setPageSize($page_size?$page_size:10);
		if($tag_name){
			$req->setTagName($tag_name);
		}
		if($tag_id){
			$req->setTagId($tag_id);
		}
		$resp = pre_resp($this->c->execute($req, session("TOP_SESSION")));
		$this->ajaxReturn($resp);
	}
	public function remove_tag(){
	    $tag_id = I("tag_id");
	    Vendor('taobaosdk/top/request/TmallPromotagTagRemovetagRequest');
	    $req = new \TmallPromotagTagRemovetagRequest;
	    $req->setTagId($tag_id);
	    $resp = pre_resp($this->c->execute($req, session("TOP_SESSION")));
	    $this->ajaxReturn($resp);
	}
	public function save_tag_to_database(){
		$tag_name = I("tag_name");
		$tag_desc = I("tag_desc");
		$start_time = date("Y-m-d H:i:s",(I("start_time")));
		$end_time = date("Y-m-d H:i:s",(I("end_time")));
		$countdown = I("countdown");
		$items = I("items");
		$key_words = I("key_words");
		$order_topic = I("order_topic");
		$rate_level = I("rate_level");
		$tag_family = I("tag_family");
		$payment = I("payment");
		$task_type = I("task_type");
		
		$tag_id = I("tag_id");
		$re = new \StdClass();

		$TAG = M("Tags");
		$data_tag["sid"]=session("SHOP_ID");
		$data_tag["tag_id"]=$tag_id;
		$data_tag["tag_name"]=$tag_name;
		$data_tag["tag_description"]=$tag_desc;
		$data_tag["start_time"]=$start_time;
		$data_tag["end_time"]=$end_time;
		$re->tag_db_id = $TAG->add($data_tag);
		if(!$re->tag_db_id){
			$re->code = 910;
			$re->sub_msg = "写入标签出错。";
		}
		
		
		$TAGTASK = M("TagTask");
		$data_tag_task["sid"]=session("SHOP_ID");
		$data_tag_task["tag_id"]=$tag_id;
		$data_tag_task["tag_name"]=$tag_name;
		$data_tag_task["tag_family"]=$tag_family;
		$data_tag_task["countdown"]=$countdown;
		$data_tag_task["order_topic"]=$order_topic;
		$data_tag_task["items"]=$items;
		$data_tag_task["rate_level"]=$rate_level;
		$data_tag_task["good_rate_key_words"]=$key_words;
		$data_tag_task["start_time"]=$start_time;
		$data_tag_task["end_time"]=$end_time;
		$data_tag_task["payment"]=$payment;
		$data_tag_task["task_type"]=$task_type;
		$re->task_id = $TAGTASK->add($data_tag_task);
		if(!$re->task_id){
			$re->code = 910;
			$re->sub_msg = "写入标签任务出错。";
		}

		$this->ajaxReturn(pre_resp($re));
	}
	public function get_tag_task(){
		$page_size = I("page_size");
		$page = I("page");
		$task_type = I("task_type");
		$data_format = I("data_format");
		$fields = I("fields");
		$fields = $fields?$fields:"task_id,tag_id,tag_name,tag_family,countdown,order_topic,rate_level,item_count,promotion_count,start_time,end_time,tag_start_time,tag_end_time,tag_desc";
		
		$TAGTASK = D("TagTaskView");
		$rule["sid"]=session("SHOP_ID");
		$rule["task_type"]=$task_type?$task_type:"auto";
		if($data_format=="form_data"){
			$rule["end_time"] = array('gt',Date("Y-m-d"));
		}
		$total = $TAGTASK->where($rule)->Count();
		$data = $TAGTASK->where($rule)->limit(($page-1)*$page_size,$page_size)->getField($fields);
		
		if($data_format=="form_data"){
			//
			foreach($data as $task){
				$tmp["label"]=$task["tag_name"]."[".$task["countdown"]."分钟]";	
				$tmp["value"]=$task["task_id"];
				$tmp["countdown"]=$task["countdown"];
				$re[]=$tmp;
			}
			$data=$re;
		}
		
		$re = new \StdClass();
		$re->data=array_values($data);
		$re->total=$total;
		if(!$re->data && $total>0){
			$re->code = 910;
			$re->sub_msg = "读取数据出错";
		}
		$this->ajaxReturn(pre_resp($re));
	}
	public function get_tag_task_items(){
		$form_data = I("form_data");
		$prom_id = I("prom_id");
		$fields = I("fields");
		
		$ITEMVIEW = D("TagTaskItemsView");
		$rule["sid"]=session("SHOP_ID");
		$rule["tag_task_id"]=$prom_id;
		$total = $ITEMVIEW->where($rule)->Count();
		if($total>0){
			$items = $ITEMVIEW->where($rule)->limit("10")->getField('id,pic_url,price,num_iid,title,promotion_type,promotion_value');
		}else{
			$items = Array();
		}
		foreach($items as $key=>$item){
			if($item["promotion_type"]==1){
				$items[$key]["final_price"] = ($item["price"]*$item["promotion_value"]/1000)/100;
			}else{
				$items[$key]["final_price"] = ($item["price"]-$item["promotion_value"])/100;
			}
			$items[$key]["price"]=$item["price"]/100;
		}
		
		$re = new \StdClass();
		$re->data=array_values($items);
		$re->total=$total;
		if(!$re->data && $total>0){
			$re->code = 910;
			$re->sub_msg = "读取数据出错";
		}
		$this->ajaxReturn(pre_resp($re));
	}
	public function edit_tag_task(){
		$task_id = I("task_id");
		$start_time = date("Y-m-d H:i:s",(I("start_time")));
		$end_time = date("Y-m-d H:i:s",(I("end_time")));
		$items = I("items");
		$key_words = I("key_words");
		$order_topic = I("order_topic");
		$rate_level = I("rate_level");
		$tag_family = I("tag_family");
		$countdown = I("countdown");
		$data["start_time"]=$start_time;
		$data["end_time"]=$end_time;
		$data["countdown"]=$countdown;
		$data["items"]=$items;
		$data["rate_level"]=$rate_level;
		$data["good_rate_key_words"]=$key_words;
		$data["order_topic"]=$order_topic;
		$data["tag_family"]=$tag_family;

		$TAGTASK = M("TagTask");
		$re = new \StdClass();
		$re->status = $TAGTASK->where(Array("sid"=>session("SHOP_ID"),"id"=>$task_id))->save($data);

		if(!$re->status){
			$re->code=910;
			$re->sub_msg="抱歉，保存出错。您也许没有修改任何参数！";
		}
		
		$this->ajaxReturn(pre_resp($re));
	}
	public function remove_tag_task(){
		$task_id = I("task_id");
		$tag_id = I("tag_id");
		$TAGTASK = M("TagTask");
		$TAG = M("Tags");
		$TAG->where(Array("tag_id"=>$tag_id,"sid"=>session("SHOP_ID")))->save(Array("is_delete"=>true));
		$re = new \StdClass();
		$re->status = $TAGTASK->execute("INSERT INTO __TABLE___removed  (`id`, `sid`, `tag_id`, `tag_name`, `tag_family`, `countdown`, `order_topic`, `rate_level`, `good_rate_key_words`, `item_count`, `promotion_count`, `start_time`, `end_time`,`payment`,`task_type`) SELECT * FROM __TABLE__ where `id`=".(int)$task_id);
		if(!($re->status===false)){
			$re->status = $TAGTASK->where(Array("id"=>$task_id,'sid'=>session("SHOP_ID")))->delete();
		}
		if(!$re->status){
			$re->code=910;
			$re->sub_msg="抱歉，删除出错！您是否已经删除过这条数据了？";
		}
		
		$this->ajaxReturn(pre_resp($re));
	}
	public function get_tag_log(){
		$id = I("id");
		$page_size = I("page_size");
		$page = I("page");
		$action = I("action");
		$search = I("search");
		
		$LOG = M("UserAddTagLog");
		$where["tag_id"]=$id;
		$where["sid"]=session("SHOP_ID");
		if($action=="add" || $action=="del"){
			$where["tag_action"]=$action;
		}
		if($action=="timeout"){
			$where["UNIX_TIMESTAMP()"]=Array("EXP",">UNIX_TIMESTAMP(add_time)+countdown*60");
			$where["tag_action"]="add";
		}
		if($search!=""){
			$where["buyer_nick"]=trim($search);
		}
		$total = $LOG->where($where)->count();
		$logs = $LOG->where($where)->order("id DESC")->limit(($page-1)*$page_size,$page_size)->getField("`id`, `tag_id`, `tag_name`, `tag_action`, `add_time`, `countdown`, `remove_time`, `buyer_nick`, `seller_nick`, `oid`, `task_id`, `action_by`, `re_try`");

		$re = new \StdClass();		
		$re->data = array_values($logs);
		$re->total = $total;		
		if(!$re->data && $re->total>0){
			$re->code=910;
			$re->sub_msg="抱歉，读取数据出错";
		}
		$this->ajaxReturn(pre_resp($re));
	}
	public function remove_user_tag_manual(){
		$tag_id = I("tag_id");
		$buyer_nick = I("buyer_nick");
		if(mb_strlen($buyer_nick,'UTF8')>20){
			$is_mixnick = true;
		}
		Vendor('taobaosdk/top/request/TmallPromotagTaguserRemoveRequest');
		$req = new \TmallPromotagTaguserRemoveRequest;
		$req->setTagId($tag_id);
		$req->setNick($buyer_nick);
		if($is_mixnick){
			$req->putOtherTextParam("top_mix_params", "nick");
		}
		$resp = pre_resp($this->c->execute($req, session("TOP_SESSION")));
		$this->ajaxReturn($resp);
	}
	public function stop_user_tag_auto_task(){
		$log_id = I("log_id");
		
		// $RMT = M("UserAddTagLogRemoveTime");
		// $data["add_tag_log_id"]=$log_id;
		// $data["remove_time"]=date("Y-m-d H:i:s");
		// $data["status"]='success';
		// $rmt_success = $RMT->add($data);
		
		$LOG = M("UserAddTagLog");
		$tag_action = $LOG->where(Array("id"=>$log_id))->getField("tag_action");
		if($tag_action=="del"){
			$re = new \StdClass();	
			$re->code=910;
			$re->sub_msg="该用户的折扣已经结束了";
			$this->ajaxReturn(pre_resp($re));
			die();
		}
		$state["action_by"]=session("VISITOR_NICK");
		$state["tag_action"]="del";
		$state["remove_time"]=date("Y-m-d H:i:s");
		$log_success = $LOG->where(Array("id"=>$log_id,"sid"=>session("SHOP_ID")))->save($state);
			
		// $MEM = M("UserAddTagLogInMemory");
		// $mem_success = $MEM->where(Array("id"=>$log_id,"sid"=>session("SHOP_ID")))->delete();
		
		
		$re = new \StdClass();		
		$re->is_success = $log_success;
		if(!$re->is_success){
			$re->code=910;
			$re->sub_msg="抱歉，结束任务出错！";
		}
		$this->ajaxReturn(pre_resp($re));
	}
	
	public function add_user_tag_manual(){
		$tag_id = I("tag_id");
		$buyer_nick = I("buyer_nick");
		if(mb_strlen($buyer_nick,'UTF8')>20){
			$is_mixnick = true;
		}
		Vendor('taobaosdk/top/request/TmallPromotagTaguserSaveRequest');
		$req = new \TmallPromotagTaguserSaveRequest;
		$req->setTagId($tag_id);
		$req->setNick($buyer_nick);
		if($is_mixnick){
			$req->putOtherTextParam("top_mix_params", "nick");
		}
		$resp = pre_resp($this->c->execute($req, session("TOP_SESSION")));
		$this->ajaxReturn($resp);
	}
	
	public function add_user_tag_auto_task(){
		
		$tag_id = I("tag_id");
		$buyer_nick = I("buyer_nick");
		$countdown = I("countdown");
		
		$TASK = D("TagTaskView");
		$task = current($TASK->where(Array("tag_id"=>$tag_id,"sid"=>session("SHOP_ID")))->getField("id,id,tag_name,is_vip,vip_group"));
		$tag_name = $task["tag_name"];
		$task_id = $task["id"];
		if($task["is_vip"]){
			$group = $task["vip_group"];
		}else{
			$group = "defaultService";
		}
		$LOG = M("UserAddTagLog");
		$state["action_by"]=session("VISITOR_NICK");
		$state["seller_nick"]=session("VISITOR_NICK");
		$state["sid"]=session("SHOP_ID");
		$state["tag_action"]="add";
		$state["add_time"]=date("Y-m-d H:i:s");
		$state["countdown"]=$countdown;
		$state["buyer_nick"]=$buyer_nick;
		$state["tag_id"]=$tag_id;
		$state["tag_name"]=$tag_name;
		$state["task_id"]=$task_id;
		$state["oid"]=0;
		$id = $LOG->add($state);
		
		$re = new \StdClass();		
		$re->id = $id;
		if(!$re->id){
			$re->code=910;
			$re->sub_msg="抱歉，设置任务出错！".$TASK->getDbError().$LOG->getDbError();
			$this->ajaxReturn(pre_resp($re));
			die();
		}
		
		try{
			$con = new \Stomp(C("ActiveMQ"),C("ActiveMQUser"),C("ActiveMQPass"));
			$con->send($group, json_encode(Array("add_log_id"=>$id,"sid"=>session("SHOP_ID"),"tag_id"=>$task_id,"buyer_nick"=>$buyer_nick,"is_mixnick"=>false)),array("amq-msg-type" => "text","persistent"=>"true","AMQ_SCHEDULED_DELAY"=>$countdown*60*1000));
		} catch (\StompException $e) {
			$LOG->where(Array("id"=>$add_log_id))->delete();
			$re->code = "916";
			$re->msg = "连接消息服务失败！".$e->getMessage();
			$this->ajaxReturn(pre_resp($re));
			die();
		}
		$re->code = 200;
		$this->ajaxReturn(pre_resp($re));
		
		
	}
}